from rest_framework import serializers
from django.utils import timezone
from .models import RiskIndicator, RiskAlert, RiskAssessmentResult, RiskLimit, RiskMonitoringTask
from portfolios.models import Portfolio
from users.models import User


class RiskIndicatorSerializer(serializers.ModelSerializer):
    """
    风险指标序列化器
    """
    class Meta:
        model = RiskIndicator
        fields = '__all__'
        read_only_fields = ('created_at', 'updated_at')
    
    def validate_threshold_value(self, value):
        """
        验证阈值
        """
        if value <= 0:
            raise serializers.ValidationError("阈值必须大于0")
        return value


class RiskAlertSerializer(serializers.ModelSerializer):
    """
    风险预警序列化器
    """
    portfolio_name = serializers.CharField(source='portfolio.name', read_only=True)
    indicator_name = serializers.CharField(source='indicator.name', read_only=True)
    resolved_by_name = serializers.CharField(source='resolved_by.username', read_only=True)
    
    class Meta:
        model = RiskAlert
        fields = '__all__'
        read_only_fields = ('created_at', 'resolved_at', 'resolved_by')
    
    def validate(self, data):
        """
        验证数据
        """
        if data.get('current_value') is not None and data.get('threshold_value') is not None:
            if data['current_value'] <= 0 or data['threshold_value'] <= 0:
                raise serializers.ValidationError("当前值和阈值必须大于0")
        return data


class RiskAssessmentResultSerializer(serializers.ModelSerializer):
    """
    风险评估结果序列化器
    """
    portfolio_name = serializers.CharField(source='portfolio.name', read_only=True)
    risk_metrics_display = serializers.SerializerMethodField()
    
    class Meta:
        model = RiskAssessmentResult
        fields = '__all__'
        read_only_fields = ('created_at',)
    
    def get_risk_metrics_display(self, obj):
        """
        格式化风险指标显示
        """
        if not obj.risk_metrics:
            return {}
        
        metrics = obj.risk_metrics
        display_metrics = {}
        
        # 格式化各种风险指标
        if 'var' in metrics:
            display_metrics['VaR'] = f"{metrics['var']:.2%}"
        if 'cvar' in metrics:
            display_metrics['CVaR'] = f"{metrics['cvar']:.2%}"
        if 'volatility' in metrics:
            display_metrics['波动率'] = f"{metrics['volatility']:.2%}"
        if 'sharpe_ratio' in metrics:
            display_metrics['夏普比率'] = f"{metrics['sharpe_ratio']:.2f}"
        if 'max_drawdown' in metrics:
            display_metrics['最大回撤'] = f"{metrics['max_drawdown']:.2%}"
        if 'beta' in metrics:
            display_metrics['贝塔系数'] = f"{metrics['beta']:.2f}"
        
        return display_metrics


class RiskLimitSerializer(serializers.ModelSerializer):
    """
    风险限额序列化器
    """
    portfolio_name = serializers.CharField(source='portfolio.name', read_only=True)
    utilization_percentage = serializers.SerializerMethodField()
    status_display = serializers.SerializerMethodField()
    
    class Meta:
        model = RiskLimit
        fields = '__all__'
        read_only_fields = ('created_at', 'updated_at', 'current_value', 'is_breached')
    
    def get_utilization_percentage(self, obj):
        """
        获取使用率百分比
        """
        if obj.limit_value and obj.limit_value > 0:
            return (obj.current_value / obj.limit_value) * 100
        return 0
    
    def get_status_display(self, obj):
        """
        获取状态显示
        """
        if obj.is_breached:
            return '已突破'
        elif obj.current_value / obj.limit_value > 0.8:
            return '接近限额'
        else:
            return '正常'
    
    def validate_limit_value(self, value):
        """
        验证限额值
        """
        if value <= 0:
            raise serializers.ValidationError("限额值必须大于0")
        return value


class RiskMonitoringTaskSerializer(serializers.ModelSerializer):
    """
    风险监控任务序列化器
    """
    portfolio_name = serializers.CharField(source='portfolio.name', read_only=True)
    created_by_name = serializers.CharField(source='created_by.username', read_only=True)
    duration = serializers.SerializerMethodField()
    
    class Meta:
        model = RiskMonitoringTask
        fields = '__all__'
        read_only_fields = ('created_at', 'started_at', 'completed_at', 'error_message')
    
    def get_duration(self, obj):
        """
        获取任务执行时长
        """
        if obj.started_at and obj.completed_at:
            duration = obj.completed_at - obj.started_at
            return duration.total_seconds()
        return None
    
    def validate(self, data):
        """
        验证数据
        """
        if data.get('schedule_time') and data.get('schedule_time') < timezone.now():
            raise serializers.ValidationError("计划执行时间不能早于当前时间")
        return data


class RiskDashboardSerializer(serializers.Serializer):
    """
    风险仪表板数据序列化器
    """
    total_portfolios = serializers.IntegerField()
    high_risk_portfolios = serializers.IntegerField()
    active_alerts = serializers.IntegerField()
    breached_limits = serializers.IntegerField()
    avg_risk_score = serializers.FloatField()
    risk_distribution = serializers.DictField()
    recent_alerts = RiskAlertSerializer(many=True)
    
    class Meta:
        fields = '__all__'


class PortfolioRiskSummarySerializer(serializers.Serializer):
    """
    投资组合风险摘要序列化器
    """
    portfolio_id = serializers.IntegerField()
    portfolio_name = serializers.CharField()
    risk_score = serializers.FloatField()
    risk_level = serializers.CharField()
    var_95 = serializers.FloatField()
    volatility = serializers.FloatField()
    max_drawdown = serializers.FloatField()
    active_alerts_count = serializers.IntegerField()
    breached_limits_count = serializers.IntegerField()
    last_assessment_date = serializers.DateTimeField()
    
    class Meta:
        fields = '__all__'